package updown.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import updown.constant.GeneralConstant;
import updown.constant.LogConstant;
import updown.controller.other.BaseController;
import updown.data.SseCacheData;
import updown.domain.ServiceInfo;
import updown.domain.TaskWrapper;
import updown.service.task.ServerHostService;
import updown.service.updown.DownUpServiceWithRetry;
import updown.util.RandomUtil;

/**
 * <p>Title: ww.kaixin.downupservice.controller </p>
 * <p>Description:updown: - 替换服务的 controller 接口 </p>
 *
 * @Author:jiangkaixin
 * @Date:2021/11/4
 * @Version: 1.0
 */
@Slf4j
@Controller
@RequestMapping("/restart")
public class RestartController extends BaseController {
    @Autowired
    private SseCacheData sseCacheData;

    @Autowired
    private ServerHostService serverHostService;

    @Autowired
    private DownUpServiceWithRetry downUpServiceWithRetry;

    /**
     * 服务替换
     * @param serviceName
     * @return
     */
    @GetMapping("/downUpCluster")
    @ResponseBody
    public String downUpCluster(String serviceName){
        log.info("log.info:serviceName >>>:{}",serviceName);
        // 1 创建任务
        SseEmitter sseEmitter = new SseEmitter(Long.MAX_VALUE);
        String taskId = RandomUtil.getRandomStr();
        sseCacheData.put(taskId, sseEmitter);

        // 2. 封装任务
        ServiceInfo serviceInfo = ServiceInfo.builder().serviceName(serviceName).build();
        TaskWrapper taskWrapper = TaskWrapper.builder()
                .taskId(taskId)
                .taskType(GeneralConstant.TASK_WRAPPER_DOWN_UP)
                .serviceInfo(serviceInfo).build();
        serverHostService.fillServerHosts(taskWrapper);

        downUpServiceWithRetry.executeInPool(taskWrapper);
        // 超时回调 触发
        sseEmitter.onTimeout(() -> sseCacheData.remove(taskId));
        // 结束之后的回调触发
        sseEmitter.onCompletion(() -> log.info("downUpCluster！！！"));
        addLog("服务替换：" + serviceName, LogConstant.MODULE_RESTART);
        return taskId;
    }
}
